/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.web.controller;

import cn.easyplatform.entities.beans.project.ProjectBean;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.identity.*;
import cn.easyplatform.studio.cmd.link.GetAllLinkCmd;
import cn.easyplatform.studio.cmd.taskLink.GetAllTaskLinkCmd;
import cn.easyplatform.studio.cmd.version.InitCmd;
import cn.easyplatform.studio.context.Contexts;
import cn.easyplatform.studio.utils.GlobalVariableService;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.InviteVo;
import cn.easyplatform.studio.vos.LoginUserVo;
import cn.easyplatform.studio.web.controller.admin.LoginLogListener;
import org.zkoss.util.Locales;
import org.zkoss.util.resource.Labels;
import org.zkoss.web.Attributes;
import org.zkoss.zk.ui.*;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.metainfo.ComponentInfo;
import org.zkoss.zk.ui.util.Composer;
import org.zkoss.zk.ui.util.ComposerExt;
import org.zkoss.zul.A;
import org.zkoss.zul.Include;
import org.zkoss.zul.Label;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.theme.Themes;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class LoginController implements Composer<Component>, ComposerExt<Component>, EventListener<Event> {

    private Component parentComponent;

    private Component c;

    private A register;

    private A retrieve;

    private Textbox userbox;

    private Textbox passwordbox;

    private InviteVo inviteVo;
    @Override
    public ComponentInfo doBeforeCompose(Page page, Component parent,
                                         ComponentInfo compInfo) throws Exception {
        Themes.setTheme(Executions.getCurrent(), "atrovirens_c");
        parent.addEventListener(Events.ON_OK, new EventListener<Event>() {
            @Override
            public void onEvent(Event event) throws Exception {
                Events.postEvent(new Event(Events.ON_CLICK,c));
            }
        });
        return compInfo;
    }

    @Override
    public void doAfterCompose(final Component comp) throws Exception {
        parentComponent = comp;
        Locale locale = Locales.getCurrent();
        if (locale.toString().equals("zh_HANS_CN")) {
            locale = Locale.CHINA;
            Sessions.getCurrent().setAttribute(Attributes.PREFERRED_LOCALE,
                    locale);
        }
        inviteVo = Contexts.getInvite();
        Label titleLabel = (Label) comp.query("#title");
        if (inviteVo != null) {
            LoginUserVo userVo = StudioApp.execute(new GetStudioUserCmd(inviteVo.getUserID()));
            ProjectBean projectBean = StudioApp.execute(new GetStudioProjectCmd(inviteVo.getProjectID()));
            titleLabel.setValue(Labels.getLabel("product.invite.title",
                    new Object[] {" " +userVo.getName()+" " , " " +projectBean.getName()+" "}));
        } else {
            titleLabel.setValue(Labels.getLabel("admin.loginlog.login"));
        }
        Contexts.setInvite(null);

        userbox = (Textbox) comp.query("#userId");
        passwordbox = (Textbox) comp.query("#password");
        String userId = Executions.getCurrent().getParameter("userId");
        userbox.setText(userId);
        StringBuilder sb = new StringBuilder();
        sb.append("if(this.getValue()!=''){var wgt=web.Widget.$('")
                .append(passwordbox.getUuid()).append("');wgt.focus();}");
        sb.append("else this.setErrorMessage('")
                .append(Labels.getLabel("user.name.placeholder")).append("')");
        userbox.setWidgetListener(Events.ON_OK, sb.toString());
        sb.setLength(0);

        c = comp.query("#login");
        c.addEventListener(Events.ON_CLICK, this);
        register = (A) comp.query("#register");
        register.addEventListener(Events.ON_CLICK, this);
        retrieve = (A) comp.query("#retrieve");
        if (inviteVo != null)
            retrieve.setVisible(false);
        else
            retrieve.setVisible(true);
        retrieve.addEventListener(Events.ON_CLICK, this);

        sb.append("if(this.getValue()!=''){var wgt=web.Widget.$('")
                .append(c.getUuid()).append("');wgt.fire('onClick');}");
        sb.append("else this.setErrorMessage('")
                .append(Labels.getLabel("user.password.placeholder"))
                .append("')");
        passwordbox.setWidgetListener(Events.ON_OK, sb.toString());
        userbox.setWidgetListener(
                Events.ON_OK,
                "if(jq(zk.$('$" +userbox.getId() +"')).val().length!=0){jq(zk.$('$" +passwordbox.getId() +"')).focus();}");
        passwordbox.setWidgetListener(
                Events.ON_OK,
                "if(jq(zk.$('$" +passwordbox.getId() +"')).val().length!=0){zk.$('$" +c.getId() +"').fire('onClick');}");
        //登陆前数据库验证
        StudioApp.execute(new DatabaseCompleteCmd());
    }

    @Override
    public void doBeforeComposeChildren(Component comp) throws Exception {
    }

    @Override
    public boolean doCatch(Throwable ex) throws Exception {
        return false;
    }

    @Override
    public void doFinally() throws Exception {

    }

    @Override
    public void onEvent(Event event) throws Exception {
        if (event.getTarget().equals(c)) {
            login(c, userbox, passwordbox, parentComponent, inviteVo);
        } else if (event.getTarget().equals(register)) {
            Include include = (Include) parentComponent.getRoot();
            include.setSrc("~./include/register/register1.zul");
            //Executions.sendRedirect("");
        } else if (event.getTarget().equals(retrieve)) {
            Include include = (Include) parentComponent.getRoot();
            include.setSrc("~./include/retrievePassword/retrievePassword1.zul");
            //Executions.sendRedirect("");
        }
    }

    public void login(Component com, Textbox userBox, Textbox passwordBox, Component parentCom, InviteVo invite) {
        if (Strings.isBlank(userBox.getText()))
            throw new WrongValueException(userBox, Labels
                    .getLabel("user.name.placeholder"));
        String userId = userBox.getText().trim();
        if (Strings.isBlank(passwordBox.getText()))
            throw new WrongValueException(passwordBox, Labels
                    .getLabel("user.password.placeholder"));
        String password = passwordBox.getText().trim();
        Object obj = StudioApp.execute(com, new LoginCmd(
                userId, password));
        if (obj instanceof String) {
            throw new WrongValueException(com,
                    (String) obj);
        } else {
            if (invite != null) {
                Contexts.setInvite(invite);
                Include include = (Include) parentCom.getRoot();
                include.setSrc("~./include/invite/invite.zul");
                return;
            }
            if (Contexts.getProject() == null) {
                Include include = (Include) parentCom.getRoot();
                include.setSrc("~./include/normal/product.zul");
                return;
            }

            //记录用户登入
            LoginUserVo user = Contexts.getUser();
            LoginLogListener.loginLog();
            //数据库验证
            try {
                Boolean success = StudioApp.execute(new VersionUpdateCmd());
            } catch (Exception ex) {
                StudioApp.execute(com, new LogoutCmd(true));
                WebUtils.showError(ex.getMessage());
                return;
            }
            //获取关系表
            if (GlobalVariableService.getInstance().getDataLinkVoList().size() == 0) {
                StudioApp.execute(new GetAllLinkCmd(Contexts.getProject().getId()));
                StudioApp.execute(new GetAllTaskLinkCmd(Contexts.getProject().getId()));
            }
            try {
                StudioApp.execute(new InitCmd());
            } catch (Exception ex) {
            }
            if (obj instanceof LoginUserVo) {

            } else {
                Map<String, Object> args = new HashMap<String, Object>(1);
                args.put("projects", obj);
                Executions.createComponents("~./include/projects.zul",
                        null, args);
            }
            if (!Strings.isBlank(user.getTheme())) {
                if ("atrovirens_c".equals(user.getTheme()))
                    user.setTheme("iceblue_c");
                Themes.setTheme(Executions.getCurrent(), user.getTheme());
            }
            Executions.sendRedirect("");
        }
    }
}



